package Java8NewLearn.Optional;



import org.junit.jupiter.api.Test;

import java.util.Optional;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-08 17:08
 * @description
 *
 */
public class OptionalTest {

    /*
    Optional类：为了在程序中避免出现空指针异常
    常用方法：
    Optional.of(T t):创建一个Optional实例，t必须非空
    Optional.empty():创建一个空的Optional实例
    Optional.ofNullable(T t):t可以为null
     */
    @Test
    public void test1(){
        Girl girl = new Girl();
        Optional<Girl> optionalGirl = Optional.of(girl);


    }

    @Test
    public void test2(){
        Girl girl = new Girl();
        girl=null;
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGirl);
    }

    public String getGirlName(Boy boy){
        return boy.getGirl().getName();
    }

    @Test
    public void test3(){
        Boy boy=new Boy();
        String girlName = getGirlName(boy); //这里会有空指针异常
        System.out.println(girlName);
    }

    //使用Optional优化以后的getGirlName()
    @Test
    public void test4(){
        Boy boy=null;
        String girlName=getGirlName2(boy);
        System.out.println(girlName);

        boy=new Boy();
        String girlName2=getGirlName2(boy);
        System.out.println(girlName2);

        boy=new Boy(new Girl("提亚拉"));
        String girlName3=getGirlName2(boy);
        System.out.println(girlName3);
    }

    public String getGirlName2(Boy boy){
        Optional<Boy> boyOptional=Optional.ofNullable(boy);
        //此时的boy1一定非空
        Boy boy1=boyOptional.orElse(new Boy(new Girl("斯提亚拉")));
        Girl girl = boy1.getGirl();
        //girl1一定非空
        Optional<Girl> girlOptional=Optional.ofNullable(girl);
        Girl girl1 = girlOptional.orElse(new Girl("面码"));
        return girl1.getName();
    }

}
